package com.lagou;

import com.lagou.service.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * create by tanxh on 2020-05-22
 **/

public class RpcDecoder <T> extends ByteToMessageDecoder {
    private Class<T> clazz;
    private Serializer serializer;

    public RpcDecoder(Class<T> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.readInt();
        byte[] msgInBytes = new byte[length];
        byteBuf.readBytes(msgInBytes);
        T t = serializer.deserialize(clazz, msgInBytes);
        list.add(t);
    }
}
